package amst.system;

import java.util.LinkedList;


public class SystemQueue {

	private LinkedList<Packet> queue = new LinkedList<Packet>();
    private PacketSystem psystem = null;
    //Zmienne potrzebne do obliczenia średniego opóźnienia
    private double meanPacketDelay;
    private int counter;
    
	public SystemQueue()
    {
         this.meanPacketDelay = 0;
         this.counter = 0;
    }
    public PacketSystem getPacketSystem()
    {
        return this.psystem;
    }
    public void setPacketSystem(PacketSystem ps)
    {
        this.psystem = ps;
    }
    public LinkedList<Packet> getQueue()
    {
		return queue;
	}

	public void setQueue(LinkedList<Packet> queue)
    {
		this.queue = queue;
	}
	
	public void addPacket(Packet packet)
    {
		this.queue.add(packet);
	}
	
	public Packet getPacket()
    {            
        double delay = 0;
		if(queue.size() > 0)
        {
            Packet packet = queue.poll();
            counter++;
            System.out.println("MPD: " + meanPacketDelay + ", PD: " + packet.getDelay(psystem.getPSTime()));
            delay = (meanPacketDelay*(counter - 1) 
                     + packet.getDelay(psystem.getPSTime()))/counter;
            this.meanPacketDelay = delay;
            System.out.println("MPD: " + meanPacketDelay);
            return packet;
        }
		else 
			return null;
	}
	
	public Packet checkPacket()
    {
    	if(this.queue.size() > 0)
			return this.queue.peek();
		else 
			return null;
	}
	
	public int getSize()
    {
		return this.queue.size();
	}
	public double getPacketDelay()
    {
        if (this.queue.peek() != null)
            return (int) this.queue.peek().getDelay(this.psystem.getPSTime());
        else return (int) meanPacketDelay;
	}
	public double getMeanPacketDelay()
    {
/*
        double sum = 0;
        double delay = 0;
        for (int i = 0; i < this.queue.size(); i++)
        {
            delay = (i*delay + this.queue.get(i).getDelay(this.psystem.getPSTime()))/(i+1);
        }
        return delay;
        */
/*        double delay = 0;
        int tmp = counter;
		if(this.queue.size() > 0 && meanPacketDelay == 0)
        {
            delay = (this.meanPacketDelay*tmp 
                     + this.queue.peek().getDelay(this.psystem.getPSTime()))/(tmp + 1);
            return delay;
        }
 */
        return getPacketDelay();
     //return meanPacketDelay;         
    }

	public int getCounter()
    {
            return counter;
    }
}
